<template>
  <Dialog
    v-model="dialogVisible"
    width="620px"
    :title="t('sn.add_new_sn')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    class="sn-list-dialog"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="110px">
      <el-form-item :label="t('wholesalOrder.productName')" prop="pid">
        <el-select
          v-model="form.pid"
          :placeholder="t('common.selectText')"
          filterable
          remote-show-suffix
          remote
          :disabled="snObj"
          :remote-method="getCustomerOptions"
          :loading="selectLoading"
        >
          <el-option v-for="item in userList" :key="item.id" :label="item.cname" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('purchase.sup')" prop="seller_id">
        <el-select
          v-model="form.seller_id"
          :filterable="true"
          :placeholder="t('common.selectText')"
          :clearable="false"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('sn.sn_num')" prop="number">
        <el-input
          v-model="form.number"
          type="number"
          :placeholder="t('common.inputText')"
          :disabled="snObj"
        />
      </el-form-item>
      <div
        v-if="snObj && snObj.sn_ids"
        class="h-228px overflow-y-auto flex flex-col items-center py-12px rounded-4px"
        style="border: 1px solid #e5e7ee"
      >
        <span v-for="(item, index) in snObj.sn_ids" :key="index" class="py-4px"
          >SN: {{ item }}</span
        >
      </div>
    </el-form>
    <template #footer>
      <template v-if="!snObj">
        <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }} </el-button>
        <el-button type="primary" @click="submit(formRef)"
          >{{ t('sn.confirm_generation') }}
        </el-button>
      </template>
      <template v-if="snObj">
        <el-button class="m-r-4" @click="closeDialog(formRef)"
          >{{ t('market.industryNews.close') }}
        </el-button>

        <el-button type="primary" @click="handlePrint">
          {{ t('sn.print') }}
        </el-button>
      </template>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { getSnAddApi } from '@/api/snManage'
import { getListApi } from '@/api/product'
import { getGoodsEnumApi } from '@/api/supply'
const emit = defineEmits(['refresh'])
const { t } = useI18n()

const supplierList = ref<Array<Record<string, any>>>([])
const dialogVisible = ref<boolean>(false)
const snObj = ref<any>(null)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  pid: '',
  number: 1
})

// 表单验证规则
const rules = ref<FormRules>({
  pid: [
    {
      required: true,
      message: t('common.selectText'),
      trigger: ['change']
    }
  ],
  seller_id: [
    {
      required: true,
      message: t('common.selectText'),
      trigger: ['change']
    }
  ],
  number: [
    {
      required: true,
      message: t('common.inputText'),
      trigger: ['blur']
    }
  ]
})
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const resp = await getSnAddApi(form.value)
        if (resp && resp.code === 0) {
          snObj.value = resp.data
          ElMessage.success(t('common.success'))
        }
      } catch (error) {}
    }
  })
}
const handlePrint = () => {
  // 实际项目中这里应该调用打印机API或打开打印预览
  ElMessageBox.confirm(t('sn.print_confirm'), t('common.tip'), {
    confirmButtonText: t('confirmMessage.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      // 这里调用实际的打印API
      let product_name = userList.value.find((e) => e.id == form.value.pid)?.cname
      const printData = [] as any
      snObj.value.sn_ids.forEach((element) => {
        printData.push({
          sn_code: element,
          product_name: product_name,
          lines: snObj.value.product_info
        })
      })

      const response = await fetch('http://127.0.0.1:33333/print', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(printData)
      })
      console.log('print', response)
    })
    .catch(() => {
      console.log('用户取消了打印')
    })
}
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    pid: '',
    number: 1
  }
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = (type: string, row?: Record<string, any>) => {
  snObj.value = null
}
// 商品名称异步下拉框
const selectLoading = ref<boolean>(false)
const userList = ref<Array<Record<string, any>>>([])
const getCustomerOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const userResp = await getListApi({ cname: value, pageIndex: 1, pageSize: 500 })
    userList.value = userResp.data.list || []
    selectLoading.value = false
  }
}
const getDropDownBoxInfo = async () => {
  const resp = await getGoodsEnumApi({ field: 'all' })
  supplierList.value = resp.data.supplier
}
onMounted(() => {
  getDropDownBoxInfo()
})
defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less">
.sn-list-dialog {
  .el-dialog__body {
    .el-scrollbar {
      height: initial !important;
    }
  }
}
</style>
